<?php

namespace App\Models;

use App\Http\Common\Lib\Common;
use QL\QueryList;

class Match extends BaseModel
{
	protected $validatorName = 'Match';

	/**
	 * 联赛
	 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
	 */
	public function league()
	{
		return $this->belongsTo('App\Models\League', 'league_id', 'id');
	}

	/**
	 * 比赛对应的推荐记录
	 * @return \Illuminate\Database\Eloquent\Relations\HasMany
	 */
	public function records()
	{
		return $this->hasMany('App\Models\LotteryRecord', 'match_id', 'id');
	}

	public function add($input)
	{
		$validateRes = $this->validateData($input, 'add');
		if ($validateRes['status'] != config('statusInfo.status.success')) {
			return Common::dataFormat($validateRes['status'], $validateRes['msg']);
		}
		$uniqueWhere = [
			['session', '=', $input['session']],
			['status', '>', -1],
		];
		$isUnique = $this->checkUnique('number', $input['number'], $uniqueWhere);
		if (!$isUnique) {
			return Common::dataFormat(config('statusInfo.status.repeated'), '该比赛已存在');
		}
		$input['sp1'] = $input['sp11'] . ',' . $input['sp12'] . ',' . $input['sp13'];
		$input['sp2'] = $input['sp21'] . ',' . $input['sp22'] . ',' . $input['sp23'];
		$input['die_time'] = strtotime($input['die_time']);
		$match = new Match();
		$match->setData($input);
		$res = $match->save();
		if ($res) {
			return Common::dataFormat(config('statusInfo.status.success'), config('statusInfo.msg.success'), [$this->primaryKey => $match->id]);
		} else {
			return Common::dataFormat(config('statusInfo.status.fail'), config('statusInfo.msg.fail'));
		}
	}

	public function edit($input)
	{
		$validateRes = $this->validateData($input, 'edit');
		if ($validateRes['status'] != config('statusInfo.status.success')) {
			return Common::dataFormat($validateRes['status'], $validateRes['msg']);
		}
		$match = $this->where($this->primaryKey, $input[$this->primaryKey])->where('session', $input['session'])->where('number', $input['number'])->where('status', '>', -1)->first();
		if (!$match) {
			return Common::dataFormat(config('statusInfo.status.notFound'), config('statusInfo.msg.notFound'));
		}
		$input['sp1'] = $input['sp11'] . ',' . $input['sp12'] . ',' . $input['sp13'];
		$input['sp2'] = $input['sp21'] . ',' . $input['sp22'] . ',' . $input['sp23'];
		$input['die_time'] = strtotime($input['die_time']);
		$match->setData($input);
		$res = $match->save();
		if ($res) {
			return Common::dataFormat(config('statusInfo.status.success'), config('statusInfo.msg.success'));
		} else {
			return Common::dataFormat(config('statusInfo.status.fail'), config('statusInfo.msg.fail'));
		}
	}

	/**
	 * 获取比赛详情
	 * @param $id
	 * @return array
	 */
	public function getDetail($id)
	{
		$detail = $this->where($this->primaryKey, $id)->with('league')->first();
		if (!$detail) {
			return Common::dataFormat(config('statusInfo.status,notFound'), config('statusInfo.msg,notFound'));
		}
		$detail->sp1 = explode(',', $detail->sp1);
		$detail->sp2 = explode(',', $detail->sp2);
		$lastTime = strtotime($detail->session) + 3600 * 24 - 60 * 5;
		$detail->die_time = $lastTime < $detail->die_time ? $lastTime : $detail->die_time;
		$detail->die_time = date('Y-m-d H:i:s', $detail->die_time);
		$detail->league_name = '';
		if ($detail->league) {
			$detail->league_name = $detail->league->name;
		}
		unset($detail->league);
		return Common::dataFormat(config('statusInfo.status.success'), config('statusInfo.msg.success'), $detail);
	}

	/**
	 * 设置分数
	 * @param $id
	 * @param $score
	 * @return array
	 */
	public function setScore($id, $score)
	{
		$match = $this->where($this->primaryKey, $id)->where('status', 2)->first();
		if (!$match) {
			return Common::dataFormat(config('statusInfo.status.notFound'), config('statusInfo.msg.notFound'));
		}
		$scores = explode(':', $score);
		if (count($scores) != 2) {
			return Common::dataFormat(config('statusInfo.status.wrongParam'), config('statusInfo.msg.wrongParam'));
		}
		foreach ($scores as $value) {
			if (is_numeric($value)) {
				$value = intval($value);
				if (!is_int($value) || $value < 0) {
					return Common::dataFormat(config('statusInfo.status.wrongParam'), '比分值不合法');
				}
			}
		}

		$res1 = $scores[0] - $scores[1];
		$res2 = $res1 + $match->balls;
		$sp1 = explode(',', $match->sp1);
		$sp2 = explode(',', $match->sp2);
		$results = [];
		$odds = [];
		//不让球
		if ($res1 > 0) {
			$results[0] = 1;
			$odds[0] = $sp1[0];
		} elseif ($res1 == 0) {
			$results[0] = 2;
			$odds[0] = $sp1[1];
		} else {
			$results[0] = 3;
			$odds[0] = $sp1[2];
		}
		//让球
		if ($res2 > 0) {
			$results[1] = 4;
			$odds[1] = $sp2[0];
		} elseif ($res2 == 0) {
			$results[1] = 5;
			$odds[1] = $sp2[1];
		} else {
			$results[1] = 6;
			$odds[1] = $sp2[2];
		}
		$match->result = implode(',', $results);
		$match->odds = implode(',', $odds);
		$match->status = 1;
		$match->score = $score;
		$res = $match->save();
		if ($res) {
			$recordModel = new LotteryRecord();
			$recordModel->updateRecords($id);
			return Common::dataFormat(config('statusInfo.status.success'), config('statusInfo.msg.success'));
		} else {
			return Common::dataFormat(config('statusInfo.status.fail'), config('statusInfo.msg.fail'));
		}
	}

	/**
	 * 比赛状态修改，删除、腰斩
	 * @param $id
	 * @param $opt
	 * @return array
	 */
	public function setStatus($id, $opt)
	{
		$opts = ['delete', 'stop'];
		$opt = strtolower($opt);
		if (!in_array($opt, $opts)) {
			return Common::dataFormat(config('statusInfo.status.wrongParam'), '操作方法不合法');
		}
		$match = $this->where($this->primaryKey, $id)->where('status', '>', -1)->first();
		if (!$match) {
			return Common::dataFormat(config('statusInfo.status.notFound'), config('statusInfo.msg.notFound'));
		}
		switch ($opt) {
			case 'delete':
				$match->status = -1;
				break;
			case 'stop':
				$match->status = 0;
				break;
		}
		$res = $match->save();
		if ($res) {
			if (in_array($opt, ['delete', 'stop']) && $match->records) {
				/*$recordModel = new LotteryRecord();
				$recordModel->where('match_id',$id)->where('status','>',0)->update();*/
				foreach ($match->records as $record) {
					$record->status = 0;
					$res = $record->save();
					if ($res && $record->user) {
						$user = $record->user;
						$preScore = $user->score;
						if ($user->increment('score', $record->pay_score)) {
							ScoreRecord::addRecord($user->id, $preScore, $record->pay_score, '比赛取消，返回积分', 1);
						}
					}
				}
			}
			return Common::dataFormat(config('statusInfo.status.success'), config('statusInfo.msg.success'));
		} else {
			return Common::dataFormat(config('statusInfo.status.fail'), config('statusInfo.msg.fail'));
		}
	}

	/**
	 * 通过期数获取比赛数据
	 * @param null $session
	 * @return mixed
	 */
	public function getMatchesBySession($session = null)
	{
		if (!$session) {
			$session = date('Ymd');
		}
		$matches = $this->where('status', '>', -1)
			->where('session', $session)
			->with('league')
			->get();
		$lastTime = strtotime($session) + 3600 * 24 - 60 * 5;
		foreach ($matches as $match) {
			$match->die_time = $match->die_time > $lastTime ? $lastTime : $match->die_time;
			$match->die_time = date('Y-m-d H:i', $match->die_time);
			$match->league_name = '';
			if ($match->league) {
				$match->league_name = $match->league->name;
			}
			unset($match->league);
			$match->sp1 = explode(',', $match->sp1);
			$match->sp2 = explode(',', $match->sp2);
			$match->result = explode(',', $match->result);
		}
		return $matches;
	}

	/**
	 * 获取并更新比赛数据
	 * @param null $session
	 * @return array
	 */
	public static function updateMatches($session = null)
	{
		if (!$session) {
			$session = date('Ymd');
		}
		$matches = self::getMatchesBy500($session);
		//dd($matches);
		if ($matches) {
			$leagueModel = new League();
			foreach ($matches as $key => $match) {
				$league = $leagueModel->getByName($match['league']);
				//dd($league);
				if ($league->status != 1) {
					$league->status = 1;
					$league->save();
				}
				$leagueId = $league->id;
				$whereData = [
					'league_id' => $leagueId,
					'session' => $session,
					'number' => $match['number'],
				];
				$updateData = [
					'host' => $match['host'],
					'guest' => $match['guest'],
					'balls' => $match['balls'],
					'sp1' => $match['sp11'] . ',' . $match['sp12'] . ',' . $match['sp13'],
					'sp2' => $match['sp21'] . ',' . $match['sp22'] . ',' . $match['sp23'],
					'die_time' => strtotime($match['endTime']),
				];
				self::updateOrCreate($whereData, $updateData);
			}
			unset($matches);
		}
		return Common::dataFormat(config('statusInfo.status.success'), '比赛数据更新成功');
	}

	/**
	 * 获取比赛结果并保存
	 * @param null $session
	 * @return array
	 */
	public function getMatchesResult($session = null)
	{
		if (!$session) {
			$session = date('Ymd', strtotime('-1 day'));
		}
		$matches = self::getResultsBy500($session);
		if ($matches) {
			$recordModel = new LotteryRecord();
			foreach ($matches as $key => $match) {
				$item = $this->where('session', $session)
					->where('number', $match['number'])
					->where('status', 2)
					->first();
				if (!$item) {
					continue;
				}
				$sp1 = explode(',', $item->sp1);
				$sp2 = explode(',', $item->sp2);
				$results = [];
				$odds = [];
				$scoreInfo = explode(':', $match['score']);
				if (count($scoreInfo) != 2) {
					continue;
				}
				$res1 = $scoreInfo[0] - $scoreInfo[1];
				$res2 = $res1 + $item->balls;
				//不让球
				if ($res1 > 0) {
					$results[0] = 1;
					$odds[0] = $sp1[0];
				} elseif ($res1 == 0) {
					$results[0] = 2;
					$odds[0] = $sp1[1];
				} else {
					$results[0] = 3;
					$odds[0] = $sp1[2];
				}
				//让球
				if ($res2 > 0) {
					$results[1] = 4;
					$odds[1] = $sp2[0];
				} elseif ($res2 == 0) {
					$results[1] = 5;
					$odds[1] = $sp2[1];
				} else {
					$results[1] = 6;
					$odds[1] = $sp2[2];
				}
				$item->score = $match['score'];
				$item->result = implode(',', $results);
				$item->odds = implode(',', $odds);
				$item->status = 1;
				$res = $item->save();
				if ($res) {
					$recordModel->updateRecords($item->id);
				}
			}
			unset($matches);
		}
		return Common::dataFormat(config('statusInfo.status.success'), '比赛结果更新完成');
	}

	/**
	 * 获取比赛数据
	 * @param null $session
	 * @return Array
	 */
	private static function getMatchesBy500($session = null)
	{
		if (!$session) {
			$session = date('Ymd');
		}
		$domain = 'http://trade.500.com/jczq/';
		$dateTime = strtotime($session);
		$year = date('Y', $dateTime);
		$session = date('Ymd', $dateTime);
		$date = date('Y-m-d', $dateTime);
		$ql = QueryList::get($domain, ['date' => $date]);
		$range = ".bet-main tr.bet-tb-tr[data-processdate='{$date}']";
		$rules = [
			'number' => ['td.td-no', 'text'],
			'league' => ['td.td-evt>a', 'text'],
			'endTime' => ['td.td-endtime', 'text'],
			'host' => ['td.td-team .team-l a', 'text'],
			'guest' => ['td.td-team .team-r a', 'text'],
			'balls' => ['td.td-rang .itm-rangA2', 'text', '-.ico-dg'],
			'sp11' => ['td.td-betbtn .itm-rangB1 p[data-value=\'3\']', 'data-sp'],
			'sp12' => ['td.td-betbtn .itm-rangB1 p[data-value=\'1\']', 'data-sp'],
			'sp13' => ['td.td-betbtn .itm-rangB1 p[data-value=\'0\']', 'data-sp'],
			'sp21' => ['td.td-betbtn .itm-rangB2 p[data-value=\'3\']', 'data-sp'],
			'sp22' => ['td.td-betbtn .itm-rangB2 p[data-value=\'1\']', 'data-sp'],
			'sp23' => ['td.td-betbtn .itm-rangB2 p[data-value=\'0\']', 'data-sp'],
		];
		$data = $ql->get($domain, ['date' => $date])->range($range)->rules($rules)->encoding('UTF-8', 'GB2312')->removeHead()->queryData();
		$ql->destruct();
		foreach ($data as $key => $value) {
			$data[$key]['session'] = $session;
			$data[$key]['number'] = substr($value['number'], -3);
			$data[$key]['endTime'] = $year . '-' . $value['endTime'];
			if (!$value['sp11']) {
				$data[$key]['sp11'] = $data[$key]['sp12'] = $data[$key]['sp13'] = 1;
			}
		}
		return $data;
	}

	/**
	 * 获取比赛结果
	 * @param null $session
	 * @return Array
	 */
	public static function getResultsBy500($session = null)
	{
		if (!$session) {
			$session = date('Ymd', strtotime('-1 day'));
		}
		$time = strtotime($session);
		$date = date('Y-m-d', $time);
		$domain = 'http://trade.500.com/jczq/';
		$ql = QueryList::get($domain, ['date' => $date]);
		$range = ".bet-main tr.bet-tb-tr[data-processdate='{$date}']";
		$rules = [
			'number' => ['td.td-no', 'text'],
			'league' => ['td.td-evt>a', 'title'],
			'host' => ['td.td-team .team-l a', 'text'],
			'guest' => ['td.td-team .team-r a', 'text'],
			'balls' => ['td.td-rang .itm-rangA2', 'text', '-.ico-dg'],
			'score' => ['td.td-team .score', 'text'],
		];
		$data = $ql->get($domain, ['date' => $date])->range($range)->rules($rules)->encoding('UTF-8', 'GB2312')->removeHead()->queryData();
		$ql->destruct();
		foreach ($data as $key => $value) {
			$data[$key]['session'] = $session;
			$data[$key]['number'] = substr($value['number'], -3);
		}
		return $data;
	}
}
